import {
  ForbiddenException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { SystemUserService } from '../system-user/system-user.service';
import { TeacherService } from '../teacher/teacher.service';
import { StudentService } from '../student/student.service';
import { JwtService } from '@nestjs/jwt';
import { encrypt } from '../utils/crypto';

@Injectable()
export class AuthService {
  constructor(
    private readonly systemUserService: SystemUserService,
    private readonly teacherService: TeacherService,
    private readonly studentService: StudentService,
    private readonly jwt: JwtService,
  ) {}

  async signing(createAuthDto: CreateAuthDto) {
    createAuthDto.password = encrypt(createAuthDto.password);

    switch (createAuthDto.typeNumber) {
      case 0:
        return this.student(createAuthDto);
      case 1:
        return this.teacher(createAuthDto);
      case 2:
        return this.systemUser(createAuthDto);
    }
  }

  // 学生
  async student(createAuthDto: CreateAuthDto) {
    const res = await this.studentService.loginStudent(
      createAuthDto.username,
      createAuthDto.password,
    );
    if (res) {
      const token = await this.jwt.signAsync({
        username: res.s_name,
        sub: res.sid,
        roleId: res.roles.map((r) => r.id), // 角色
      });
      return {
        token,
        userInfo: await this.studentService.findUserDetail(res.sid),
      };
    }
    return new UnauthorizedException('账号密码错误');
  }
  // 老师
  async teacher(createAuthDto: CreateAuthDto) {
    const res = await this.teacherService.loginTeacher(
      createAuthDto.username,
      createAuthDto.password,
    );
    if (res) {
      const token = await this.jwt.signAsync({
        username: res.t_name,
        sub: res.tid,
        roleId: res.roles.map((r) => r.id), // 角色
      });
      return {
        token,
        userInfo: await this.teacherService.findDetail(res.tid),
        roleId: res.roles.map((r) => r.id), // 角色
      };
    }
    return new UnauthorizedException('账号密码错误');
  }
  // 系统用户
  async systemUser(createAuthDto: CreateAuthDto) {
    const res = await this.systemUserService.loginSystemUser(
      createAuthDto.username,
      createAuthDto.password,
    );
    if (res) {
      const token = await this.jwt.signAsync({
        username: res.name,
        sub: res.id,
        roleId: res.roles.map((r) => r.id), // 角色
      });
      return {
        token,
        userInfo: await this.systemUserService.findDetail(res.id),
      };
    }
    return new UnauthorizedException('账号密码错误');
  }
}
